package com.mzl.lal4cloud.lxw4rf.service.contract.http;

import com.mzl.lal4cloud.lxw4rf.service.contract.exception.ErrorException;
import okhttp3.Response;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 三种http框架的response代理类，方便提取公共方法
 *
 * @author J_luo
 */
public class HttpResponseProxy {
    private static final Pattern PATTERN = Pattern.compile(".*filename=\"(.*)\"");

    private Response okHttpResponse;


    public HttpResponseProxy(Response okHttpResponse) {
        this.okHttpResponse = okHttpResponse;
    }

    public String getFileName() throws ErrorException {
        if (this.okHttpResponse != null) {
            return this.getFileName(this.okHttpResponse);
        }
        return null;
    }


    private String getFileName(Response response) throws ErrorException {
        String content = response.header("Content-disposition");
        return this.extractFileNameFromContentString(content);
    }

    private String extractFileNameFromContentString(String content) throws ErrorException {
        if (content == null || content.length() == 0) {
            throw new ErrorException("无法获取到文件名，content为空");
        }

        Matcher m = PATTERN.matcher(content);
        if (m.matches()) {
            return m.group(1);
        }

        throw new ErrorException("无法获取到文件名，header信息有问题");
    }

}
